package com.cntcdt.web.resource.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.data.LocalReference;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.representation.FileRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series;

import com.cntcdt.api.common.Constants;
import com.cntcdt.api.common.PlatformConstants;
import com.cntcdt.api.common.utils.GetObjectUtils;
import com.cntcdt.api.main.StaticResourceApplication;
import com.cntcdt.api.utils.CDTToken;


public abstract class BaseWebResource extends ServerResource
{
	
	protected Logger log=Logger.getLogger("com.newhuotu");
	
	public static final int RESULT_SUCC=1; //接口处理成功
	public static final int RESULT_FAIL =-1 ; //接口处理失败
	
	public static final String EVENT_NEWUSER = "新用户";
	public static final String EVENT_INSTALL = "新安装";
	public static final String EVENT_USER = "用户启动软件";
	public static final String EVENT_LOGIN = "登录";
	public static final String EVENT_BIND = "绑定";
	
	public static final String EVENT_PUSH_MSG = "发送推送消息";
	public static final String TAG_PUSH_MSG_VERSION_UPDATE = "版本更新";
	public static final String TAG_PUSH_MSG_GAME_TIPS = "活动提醒";
	public static final String TAG_PUSH_MSG_MARKET_TIPS = "道具屋提醒";
	public static final String TAG_PUSH_MSG_GAOGUAI = "搞怪提醒";
	public static final String TAG_PUSH_MSG_FUN = "搞怪";
	public static final String TAG_PUSH_MSG_LIKE = "喜欢";
	public static final String TAG_PUSH_MSG_ZAN = "赞";
	public static final String TAG_PUSH_MSG_NEARBY = "旁边";
	public static final String TAG_PUSH_MSG_FOCUS = "粉丝消息";
	
	public static final String EVENT_PUSH_IPHONE_MSG = "发送Iphone推送消息";
	
	public static final String EVENT_PUSH_MSG_GETMSG = "用户取消息";
	
	public static final String EVENT_SEND_FEED = "发送feed";
	public static final String TAG_FEED_NEW = "新用户发送";
	public static final String TAG_FEED_USER_GUIDE = "新用户引导发feed";
	public static final String TAG_FEED_SHARE_ME = "用户分享--原创";
	public static final String TAG_FEED_SHARE_FUN = "用户分享--被搞";
	public static final String TAG_FEED_SHARE_ZAN = "用户分享--赞";
	
	public static final String EVENT_FUN = "搞怪图片";
	public static final String TAG_FUN_ME = "搞怪图片--原创";
	public static final String TAG_FUN_OTHER = "搞怪图片--搞别人";
	
	public static final String EVENT_RANDOM_FUN = "随机搞怪别人";
	public static final String EVENT_LIKE = "操作--喜欢";
	public static final String EVENT_UNLIKE = "操作--不喜欢";
	public static final String EVENT_ZAN = "操作--赞";
	public static final String EVENT_PIC_DETAIL = "照片详情";
	public static final String EVENT_SQUARE_WONDERFUL = "首页-广场精彩";
	public static final String EVENT_SQUARE_ME = "首页-我的搞怪照片";
	public static final String EVENT_SQUARE_BEFUN = "首页-被搞怪照片";
	
	public static final String EVENT_MARKET = "道具屋";
	public static final String TAG_MARKET_CLASS = "类别ID=";
	public static final String TAG_MARKET_SEARCH = "搜索关键字=";
	
	public static final String EVENT_MESSAGE_SETTING = "用户设置消息开关";
	public static final String TAG_MESSAGET_SETTING_OPEN = "开启收消息";
	public static final String TAG_MESSAGET_SETTING_CLOSE = "关闭收消息";
	
	public static final String EVENT_PENDANT_DOWNLOAD = "道具下载";
	
	public static final String EVENT_SEND_SMS = "发送手机短信";
	
	public static final String EVENT_NEWS_CENTER = "消息中心";
	
	public static final String EVENT_MOBILE = "填写电话号码";
	
	public static final int STATIS_NOSNS = -100;
	
	public static final String LANG_ZH = "zh";
	public static final String LANG_CN = "cn";
	public static final String LANG_JP = "jp";
	public static final String LANG_JA = "ja";
	public static final String LANG_EN = "en";
	public static final String LANG_KO = "ko";
	public static final String LANG_TW = "tw";
	public static final String LANG_HK = "hk";
	
	public static final String FACEBOOK_TYPE_TAKE = "take";
	public static final String FACEBOOK_TYPE_LIKE = "like";
	public static final String FACEBOOK_TYPE_SHARE = "share";
	public static final String FACEBOOK_TYPE_RECOMMEND = "recommend";
			
	protected MediaType mediaType;
	// 请求json还是xml
	protected String format;
	// 请求类型
	protected String category;
	// 查询字符串中的参数信息
	protected Map<String, Object> paramsMap;
	protected RestletFileUpload rfuPic = new RestletFileUpload();
	protected List<FileItem> fiList;
	protected Form form;
	protected String callback;
	protected String requestPath;
	protected String realip;
	protected Request request;
	protected String channelId = "";
	protected String phonecode = "";
	
	
	protected String platform = "";
	protected int platformInt = -100;
	protected String device = "";
	protected String softversion = "";
	protected String channel = "";
	protected String origin = "";
	protected String deviceId = "";
	protected String accessToken = "";
	protected double x;
	protected double y;
	
	protected String appName = "";
	protected String locale = "";
	protected String countryCode = "";
	protected String client_id = "";
	protected String client_secret = "";
	protected int testCode = 0;
	protected int userId = 0;
	protected String password;
	

	protected BaseWebResource()
	{
		paramsMap = new HashMap<String, Object>();
		mediaType = MediaType.APPLICATION_JSON;
	}

	protected void doInit() throws ResourceException
	{
		super.doInit();
		request = getRequest();
		requestPath = request.getResourceRef() == null ? "" : request
				.getResourceRef().getPath();
		rfuPic.setHeaderEncoding("UTF-8");
		rfuPic.setFileSizeMax(Constants.UPLOAD_FILE_SIZE * 1024 * 1024);// 每张图片最大2M
		rfuPic.setFileItemFactory(new DiskFileItemFactory());
		rectifyParamMap(request);
		Map<String, Object> paramMap = request.getAttributes();
		format = paramMap.get("format") == null ? "" : (String) paramMap
				.get("format");
		mediaType = MediaType.APPLICATION_JSON;
		if (StringUtils.equalsIgnoreCase(format, "json"))
		{
			mediaType = MediaType.APPLICATION_JSON;
		}
		else
		{
			mediaType = MediaType.APPLICATION_XML;
		}
		initParameter();
		initParams(request);
	}
	

	/**
	 * 初始化参数
	 * 
	 * @author 叶佳鑫
	 * @create Feb 17, 2011
	 * @param request
	 */
	protected abstract void initParams(Request request);

	private void rectifyParamMap(Request request)
	{
		// 取头部的信息
		Series sheaders = (Series)getRequest().getAttributes().get(  
	            "org.restlet.http.headers");
		Map<String,String> headers = sheaders.getValuesMap();
//		Object obj = request.getAttributes().get(
//				"org.restlet.http.headers");
//		Form headers = new Form(obj.toString());
//		if (headers != null)
//		{
//			for (String name : headers.getNames())
//			{
//				paramsMap.put(name, headers.getFirstValue(name));
//				if (name.contains("X-Real-IP"))
//				{
//					realip = headers.getFirstValue(name);
//				}
//			}
//		}
		/**
		 * 根据不同的请求类型，处理参数的获取
		 */
		// 取get请求的信息
		if (request.getMethod().equals(Method.GET))
		{
			form = request.getResourceRef().getQueryAsForm();
			for (String name : form.getNames())
			{
				try {
					//paramsMap.put(name,form.getFirstValue(name));
					paramsMap.put(name, java.net.URLDecoder.decode( form.getFirstValue(name),"utf-8"));
				} catch (Exception e) {
					paramsMap.put(name,form.getFirstValue(name));
					//e.printStackTrace();
				}
			}
		}
		else if (request.getMethod().equals(Method.POST))
		{
			// 取POST请求的信息
			if (headers != null)
			{
				if (headers.get("Content-Type") != null && !headers.get("Content-Type").startsWith(MediaType.MULTIPART_FORM_DATA.getName()))
				{
					// 如果不是上传文件(multipart/form-data)
					// 将form中的数据全部转移到paramMap中.
					if (request.getEntity().isAvailable())
					{
						form = new Form(request.getEntity());
						paramsMap.putAll(form.getValuesMap());
					}
				}
				else
				{
					try
					{
						fiList = rfuPic.parseRequest(getRequest());
					}
					catch (FileUploadException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
						form = new Form(request.getEntity());
					}
				}
			}
		}
//		if (headers != null && headers.getFirstValue(SignatureValidFilter.ACCESS_TOKEN) != null)
//		{
//			paramsMap.put(SignatureValidFilter.ACCESS_TOKEN, headers.getFirstValue(SignatureValidFilter.ACCESS_TOKEN));
//		}
	}
	
	/**
	 * a/b test使用的方法
	 * @author Kin
	 * @create 2012-8-29 下午3:53:13
	 * @param deviceId
	 * @return int
	 */
	public static int newGetUserClassCode(String deviceId)
	{
		int tempInt = 0;
		try
		{
			String str = deviceId.substring(deviceId.lastIndexOf("-") + 1);

			for (int i = 0; i < str.length(); i++)
			{
				char temp = str.charAt(i);
				if (temp <= 57 && temp >= 48)
				{
					tempInt += temp;
				}
			}
		}
		catch (Exception e)
		{

		}
		return tempInt % 2;
	}

	
	protected void initParameter()
	{
		if(fiList==null)
		{
			platform = GetObjectUtils.toString(paramsMap.get("platform"), "");
			device = GetObjectUtils.toString(paramsMap.get("device"), "");
			softversion = GetObjectUtils.toString(paramsMap.get("softversion"), "");
			channel = GetObjectUtils.toString(paramsMap.get("channel"), "");
			origin = GetObjectUtils.toString(paramsMap.get("origin"), "");
			deviceId = GetObjectUtils.toString(paramsMap.get("phonecode"), "");
			phonecode = deviceId;
			accessToken = GetObjectUtils.toString(paramsMap.get("access_token"), "");
			if(accessToken.equals("")){
				accessToken = GetObjectUtils.toString(paramsMap.get("x:access_token"), "");
			}
			appName = GetObjectUtils.toString(paramsMap.get("app_name"), "");
			locale = GetObjectUtils.toString(paramsMap.get("locale"), "");
			countryCode = GetObjectUtils.toString(paramsMap.get("countrycode"), "");
			client_id = GetObjectUtils.toString(paramsMap.get("client_id"), "");
			client_secret = GetObjectUtils.toString(paramsMap.get("client_secret"), "");
		}
		else
		{
			for(FileItem fi:fiList)
			{
				String name = fi.getFieldName();
				if(StringUtils.equalsIgnoreCase(name,"platform"))
				{
					platform = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"device"))
				{
					device = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"softversion"))
				{
					softversion = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"channel"))
				{
					channel = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"origin"))
				{
					origin = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"access_token"))
				{
					accessToken = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"phonecode"))
				{
					deviceId = fi.getString();
					phonecode = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"app_name"))
				{
					appName = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"locale"))
				{
					locale = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"countrycode"))
				{
					countryCode = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"client_id"))
				{
					client_id = fi.getString();
					continue;
				}
				if(StringUtils.equalsIgnoreCase(name,"client_secret"))
				{
					client_secret = fi.getString();
					continue;
				}
			}
		}
		if(platform.toLowerCase().trim().equals("android"))
		{
			platformInt = PlatformConstants.PLATFORM_ANDROID;
		}
		else if(platform.toLowerCase().trim().equals("iphone") || platform.toLowerCase().trim().equals("ipad"))
		{
			platformInt = PlatformConstants.PLATFORM_IOS;
		}
		else if(platform.toLowerCase().trim().contains("s60"))
		{
			platformInt = PlatformConstants.PLATFORM_SYMBIAN;
		}
		testCode = newGetUserClassCode(deviceId);
		log.debug("platform="+platform+" appName="+appName+" locale="+locale);
	}
	
	protected boolean statis(String item)
	{
		return statis(item,"",STATIS_NOSNS);
	}

	protected boolean statis(String item, String tag)
	{
		return statis(item,tag,STATIS_NOSNS);
	}
	
	protected boolean statis(String item, String tag,int sns)
	{
		/**
		 * 新增一条统计记录
		 * @param item		统计项
		 * @param value 	指（可选）
		 * @param platform	平台（枚举值）（可选）
		 * @param device	设备（可选）
		 * @param version	版本（可选）
		 * @param channel	渠道（可选）
		 * @param sns		相关SNS社区（枚举值）（可选）
		 * @param origin	来源（可选）
		 * @param app		APP名称（可选）
		 * @param region	地区（可选）
		 * @param language	语言（可选）
		 * @param deviceId	设备唯一ID（可选）
		 * @param sid		用户认证标识（可选）
		 * @return			调用是否成功
		 */
		//return Factory.getPlatformConstants().addStat(item, tag, platformInt, device, softversion, channel, sns, origin,appName,countryCode,locale, deviceId,accessToken,testCode);
	   return false;
	}
	
	protected long statisWithId(String item, String tag)
	{
		return statisWithId(item,tag,-100);
	}
	
	protected long statisWithId(String item, String tag,int sns)
	{
	   //	return Factory.getPlatformConstants().addStatForResult(item, tag, platformInt, device, softversion, channel, sns, origin,appName,countryCode,locale, deviceId,accessToken,testCode);
	    return 0L;
	}
	
	protected boolean statisSuccess(long id)
	{
		//return Factory.getPlatformConstants().updateStatSuccess(id);
		return true;
	}
	
	protected boolean statisFail(long id,String errorLog)
	{
		//return Factory.getPlatformConstants().updateStatFailure(id,errorLog);
		return true;
	}
	
	protected String sendSns(String item,String tag,int sns,String snsString,int userId,String content,String picKey,String link,String type)
	{
		Map<String,String> stat = new HashMap<String,String>();
		//统计数据
		stat.put("accesstoken", accessToken);
		stat.put("item", item);
		stat.put("device", device);
		stat.put("softversion", softversion);
		stat.put("channel", channel);
		stat.put("origin", origin);
		stat.put("deviceId", deviceId);
		stat.put("tag", tag);
		stat.put("platform", platformInt+"");
		stat.put("sns", sns+"");
		stat.put("language", locale);
		stat.put("app", appName);
		stat.put("region", countryCode);
		stat.put("testcode", testCode+"");
		String platformSns = "";
////		if(platform.toLowerCase().trim().equals("android"))
////		{
//			platformSns = SnsServiceFactory.ANDROID_PLATFORM;
//		}
//		else if(platform.toLowerCase().trim().equals("iphone") || platform.toLowerCase().trim().equals("ipad"))
//		{
		//已经app统一为使用的iphone了，设置成这样才能同步
			//platformSns = SnsServiceFactory.IOS_PLATFORM;
//		}
//		else if(platform.toLowerCase().trim().contains("s60"))
//		{
//			platformSns = SnsServiceFactory.SYMBIAN_PLATFORM;
//		}
		//SnsClient snsClient = SnsServiceFactory.getSnsClient(snsString, SnsServiceFactory.HUOTU_BUSINESS, platformSns,SnsServiceFactory.OATU_2);
		/**
		 * 
		 * @param tokenKey     外部社区 acceestoken
		 * @param refreshToken 外部社区 refreshToken
		 * @param profileId    外部社区 profileId ：用户唯一ID 
		 * @param content      发送内容
		 * @param fileKey      发送内容 发送图片 key ：04f56a7fd4594071967130f20d28599a0004.jpg
		 * @param stat         统计Map<String,String> stat 
		 * @return
		 */
		//String returnStr = snsClient.SendFile("", "", userId+"",content, picKey,link,type, stat);
		//System.out.print("returnStr=================="+returnStr);
		//return returnStr;
		return "";
	}
	
	
	@Get
	public Representation get() throws ResourceException
	{
		BaseResultModel br = new BaseResultModel();
		getMethod(br);
		
	    Representation movieFtl = new FileRepresentation(  
	    		StaticResourceApplication.ROOT_URI+br.getHtmlPath(),MediaType.TEXT_HTML);
	    return new TemplateRepresentation( movieFtl , br.getDataModel() , MediaType.TEXT_HTML) ; 
	}
	
	@Post
	public Representation post () throws ResourceException
	{
		BaseResultModel br = new BaseResultModel();
		postMethod(br);
		
	    Representation movieFtl = new FileRepresentation(  
	    		StaticResourceApplication.ROOT_URI+br.getHtmlPath(),MediaType.TEXT_HTML);
	    return new TemplateRepresentation( movieFtl , br.getDataModel() , MediaType.TEXT_HTML) ; 
	}
	
	/**
	 * 处理get请求的方法
	 * @param json
	 * @return json将返回到客户端
	 */
	protected abstract void getMethod(BaseResultModel br);
	
	/**
	 * 处理post请求的方法
	 * @param json
	 * @return json将返回到客户端
	 */
	protected abstract void postMethod(BaseResultModel br);
	

	
	
	
	private JSONObject auth(){
		log.debug("paramsMap==="+paramsMap+"  accessToken="+accessToken);
		JSONObject json = null;
		if(accessToken==null && "".equals(accessToken))
		{
			json = new JSONObject();
			json.put("result", RESULT_FAIL);
			json.put("msg", "缺少access_token参数");
			return json;
		}
		
		try{
			//这个判断是debug用
			
			if(accessToken.startsWith("100000")){
				userId = Integer.valueOf(accessToken);
			}else{
				userId = CDTToken.decodeToken(accessToken);
				password = CDTToken.decodeTokenGetPassword(accessToken);
			}
			log.debug("request userId======="+userId);
		}catch(Exception e){
			e.printStackTrace();
		}
		if(userId<1){
			json = new JSONObject();
			json.put("result", RESULT_FAIL);
			json.put("msg", "access_token参数出错");
			return json;
		}
		return json;
		
	}

	public String getParameter(String paramName , String defaultValue){
		return  GetObjectUtils.toString(paramsMap.get(paramName), defaultValue);
	}
	public int getParameter(String paramName , int defaultValue){
		return GetObjectUtils.toInt(paramsMap.get(paramName), defaultValue);
	}
	public double getParameter(String paramName , double defaultValue){
		return  GetObjectUtils.toDouble(paramsMap.get(paramName), defaultValue);
	}
	
	
	public JSONObject failRequest(String msg , JSONObject json){
		json.put("msg",msg);
		json.put("result", RESULT_FAIL);
		return json;
	}
	
	public JSONObject succRequest(String msg , JSONObject json){
		json.put("msg",msg);
		json.put("result", RESULT_SUCC);
		return json;
	}
	
}